package dao;

import model.Chapter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.C3P0Util;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class ChapterDAO {
    /**
     * 根据漫画id获得该漫画下的所有章节
     *
     * @param comic_id 漫画id
     * @return 章节list
     */
    public List<Chapter> getComicChapterList(int comic_id) {
        List<Chapter> list1 = new ArrayList<Chapter>();
        QueryRunner queryRunner = new QueryRunner(C3P0Util.getDataSource());
        String sql = "select * from chapter where comic_id=? order by comic_index";
        Object[] params = {comic_id};
        try {
            list1 = (List<Chapter>) queryRunner.query(sql, new BeanListHandler(Chapter.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list1;
    }

    /**
     * 根据章节id获得临近的章节
     *
     * @param chapterId 章节id
     * @return 下一章节
     */
    public List<Chapter> getNearChapter(int chapterId) {
        List<Chapter> chapters = new ArrayList<Chapter>();
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        String sql = "\n" +
                "select B.* from chapter A,chapter B where A.id=? and B.comic_id=A.comic_id and (B.comic_index=A.comic_index+1 or B.comic_index=A.comic_index or B.comic_index=A.comic_index-1)";
        Object[] params = {chapterId};
        try {
            chapters = (List<Chapter>) qr.query(sql, new BeanListHandler(Chapter.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return chapters;
    }

    /**
     * 根据章节id获得该章节的详情
     *
     * @param chapterId 章节id
     * @return Chapter
     */
    public Chapter getChapterDetail(int chapterId) {
        Chapter chapter;
        Object[] params = {chapterId};
        String sql = "select * from chapter where id=?";
        chapter = DAO_common.beanQuery(sql, Chapter.class, params);
        return chapter;
    }
}
